package autopeople.tools;

import java.io.FileOutputStream;

import javax.inject.Named;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;

@Named
public class TransformerTool {
	protected static Logger logger = Logger.getLogger("controller");

	public void transformXMLandXSLTIntoJspFileToBeUsedAsView(Source xsltSource,
			Source xmlSource) throws Exception {
		final Transformer transformer = getTransformer(xsltSource);
		createJspFile(xmlSource, transformer);
	}

	/* Get Transformer from an xsltSource */
	private Transformer getTransformer(Source xsltSource) throws Exception {
		logger.debug("getTransformer");
		// Get transformers from javax.xml.transfom (jdk library)
		final TransformerFactory transFact = TransformerFactory.newInstance();
		final Transformer transformer = transFact.newTransformer(xsltSource);

		// We have Chinese characters, so we will have to use UTF-16 encoding
		transformer.setOutputProperty("encoding", "UTF-16");

		return transformer;
	}

	private void createJspFile(Source xmlSource, Transformer t)
			throws Exception {
		final String jspfile = getClass().getResource("/jsp/people.jsp").getFile();
		logger.debug("createJspFile" + jspfile);
		t.transform(xmlSource, new StreamResult(new FileOutputStream(jspfile)));
	}
}
